package com.example.emos.api.common.util;

import com.example.emos.api.exception.EmosException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

/**
 * JSON工具类
 *
 * @author Shiwei Xu
 * @date 2019/11/21
 */
public class JsonUtils {

    private static ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
    }
//    @Autowired
//    private ObjectMapper objectMapper;

//    public static ObjectMapper getObjectMapper() {
////        if (objectMapper == null) {
////            objectMapper = SpringContextUtils.getBean(ObjectMapper.class);
////        }
//        return objectMapper;
//    }

    /**
     * 转换Json
     *
     * @param object 待序列化对象
     * @return JSON字符串
     */
    public static String toJson(Object object) {
        if (object == null) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new EmosException("JSON序列化异常", e);
        }
    }

    /**
     * Json转换为对象 转换失败返回null
     *
     * @param json 待反序列化的JSON字符串
     * @return 对象
     */
    public static Object parse(String json) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            return objectMapper.readValue(json, Object.class);
        } catch (Exception e) {
            throw new EmosException("JSON反序列化异常", e);
        }
    }

    /**
     * Json转换为对象 转换失败返回null
     *
     * @param json  待反序列化的JSON字符串
     * @param clazz 类型
     * @return 对象
     */
    public static <T> T parse(String json, Class<T> clazz) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new EmosException("JSON反序列化异常", e);
        }
    }

    /**
     * Json转换为对象 转换失败返回null
     *
     * @param json         待反序列化的JSON字符串
     * @param valueTypeRef 类型
     * @return 对象
     */
    public static <T> T parse(String json, TypeReference<T> valueTypeRef) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            return objectMapper.readValue(json, valueTypeRef);
        } catch (Exception e) {
            throw new EmosException("JSON反序列化异常", e);
        }
    }
}
